package com.solocredit.finance.utils

import android.content.Intent
import android.net.Uri
import android.provider.ContactsContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.solocredit.finance.base.utils.log.MullaLog
import com.solocredit.finance.mvp.ProAct

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/20 15:23
 * @Annotation：选择联系人
 */
class MullaChoosePhoneBookUtils(private val proAct: ProAct) {

    // 临时回调接收器
    private var pickPhoneBookCallback: ((userName: String, userMobile: String) -> Unit)? = null

    // 通讯录启动器
    private val phonebookLauncherBus = proAct.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it == null || it.resultCode != AppCompatActivity.RESULT_OK)
            return@registerForActivityResult
        it.data?.data?.let { uri ->
            pickPhoneBookAction(uri) // 从返回的Uri解析出联系人
        }
    }

    /** 从通讯录选取联系人 */
    fun startPickPhoneBook(callback: (userName: String, userMobile: String) -> Unit) {
        pickPhoneBookCallback = callback
        try {
            phonebookLauncherBus.launch(Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI))
        } catch (e: Exception){
            MullaLog.e("Pick Contact error: ${e.message}")
        }
    }

    /**
     * 解析联系人数据
     */
    private fun pickPhoneBookAction(contactUri: Uri){
        var displayName = ""
        var phoneNumber = ""
        try {
            val projection = arrayOf(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER)
            proAct.contentResolver.query(contactUri, projection, null, null, null)?.use {
                if (it.moveToFirst()) {
                    val nameIndex = it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                    displayName = it.getString(nameIndex)
                    val phoneIndex = it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                    phoneNumber = it.getString(phoneIndex)
                }
            }
        } catch (e: Exception){
            displayName = ""
            phoneNumber = ""
        }
        pickPhoneBookCallback?.invoke(displayName, phoneNumber)
    }
}